package com.xs.ai.services;

import com.xs.ai.dto.EmailAnalysisResult;
import com.xs.ai.dto.ExtractedDeadline;
import com.xs.ai.dto.MeetingAnalysisResult;
import com.xs.ai.dto.ReplySuggestion;
import com.xs.ai.entity.CalendarEvent;
import com.xs.ai.entity.Email;
import com.xs.ai.entity.Task;
import com.xs.ai.entity.User;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class AutomationWorkflowService {
    
    private final EmailAnalysisService emailAnalysisService;
    private final CalendarOptimizationService calendarService;
    private final EmailService emailService;
    private final TaskService taskService;
    private final NotificationService notificationService;
    
    /**
     * 处理新收到的邮件 - 完整自动化流程
     */
    @Async
    @Transactional
    public void handleIncomingEmail(Email email, User user) {
        log.info("开始自动化处理邮件: {}", email.getMessageId());
        
        AIWorkflowExecution execution = new AIWorkflowExecution();
        execution.setUserId(user.getId());
        execution.setWorkflowType("email_processing");
        execution.setTriggerType("email_received");
        
        try {
            // 1. AI分析邮件
            EmailAnalysisResult analysis = emailAnalysisService.analyzeEmail(email, user);
            execution.addAction("analyze_email", analysis);
            
            // 2. 根据优先级和类别执行不同操作
            switch (analysis.getPriority()) {
                case URGENT_CRITICAL:
                    handleUrgentEmail(email, analysis, user, execution);
                    break;
                    
                case HIGH_IMPORTANCE:
                    handleHighPriorityEmail(email, analysis, user, execution);
                    break;
                    
                case MEDIUM_IMPORTANCE:
                    handleMediumPriorityEmail(email, analysis, user, execution);
                    break;
                    
                case LOW_IMPORTANCE:
                    handleLowPriorityEmail(email, analysis, user, execution);
                    break;
                    
                case AUTO_ARCHIVE:
                    handleAutoArchiveEmail(email, analysis, user, execution);
                    break;
            }
            
            // 3. 处理特定类别
            if ("meeting_request".equals(analysis.getCategory())) {
                handleMeetingRequest(email, analysis, user, execution);
            }
            
            // 4. 提取并创建任务
            if (!analysis.getExtractedDeadlines().isEmpty()) {
                createTasksFromDeadlines(email, analysis, user, execution);
            }
            
            // 5. 如果需要决策，创建决策卡片
            if (analysis.isRequiresDecision()) {
                createDecisionCard(email, analysis, user, execution);
            }
            
            execution.setStatus("success");
            log.info("邮件自动化处理完成");
            
        } catch (Exception e) {
            log.error("邮件自动化处理失败: {}", e.getMessage(), e);
            execution.setStatus("failed");
            execution.setErrorMessage(e.getMessage());
        } finally {
            workflowExecutionRepository.save(execution);
        }
    }
    
    /**
     * 处理紧急邮件
     */
    private void handleUrgentEmail(Email email, EmailAnalysisResult analysis, 
                                   User user, AIWorkflowExecution execution) {
        // 1. 立即推送通知
        notificationService.sendUrgentNotification(user, 
            "紧急邮件", 
            String.format("来自 %s: %s", email.getSenderName(), analysis.getSummary())
        );
        execution.addAction("send_urgent_notification", "已发送紧急通知");
        
        // 2. 生成快速回复建议
        List<ReplySuggestion> suggestions =
            emailAnalysisService.generateReplySuggestions(email, user);
        execution.addAction("generate_reply_suggestions", suggestions);
        
        // 3. 如果AI高度确信可以自动回复（confidenceScore > 0.9）
        if (analysis.getConfidenceScore() > 0.9 && 
            user.getAiPreferences().isAutoReplyUrgent()) {
            
            ReplySuggestion bestSuggestion = suggestions.get(0);
            emailService.sendReply(email, bestSuggestion.getBody(), user);
            execution.addAction("auto_reply", "已自动发送回复");
            
            // 记录用户决策供后续学习
            behaviorLearningService.recordDecision(user.getId(), 
                "auto_reply", "urgent_email", true);
        }
    }
    
    /**
     * 处理高优先级邮件
     */
    private void handleHighPriorityEmail(Email email, EmailAnalysisResult analysis,
                                        User user, AIWorkflowExecution execution) {
        // 1. 推送通知（非紧急级别）
        notificationService.sendHighPriorityNotification(user,
            String.format("%s 发来重要邮件", email.getSenderName()),
            analysis.getSummary()
        );
        
        // 2. 如果可以委托
        if (analysis.isCanDelegate() && analysis.getSuggestedDelegateTo() != null) {
            // 查找合适的委托人
            User delegate = findBestDelegate(analysis.getSuggestedDelegateTo(), user);
            
            if (delegate != null) {
                // 创建委托任务
                Task delegatedTask = taskService.createDelegatedTask(
                    email, delegate, analysis.getSuggestedActions().get(0).getDescription()
                );
                execution.addAction("delegate_task", 
                    String.format("已委托给 %s", delegate.getName()));
                
                // 通知委托人
                notificationService.sendDelegationNotification(delegate, delegatedTask);
            }
        }
        
        // 3. 生成回复建议
        List<ReplySuggestion> suggestions = 
            emailAnalysisService.generateReplySuggestions(email, user);
        execution.addAction("generate_reply_suggestions", suggestions);
    }
    
    /**
     * 处理会议请求
     */
    private void handleMeetingRequest(Email email, EmailAnalysisResult analysis,
                                     User user, AIWorkflowExecution execution) {
        // 从邮件中提取会议信息（假设已解析）
        CalendarEvent meetingRequest = extractMeetingFromEmail(email);
        
        // 使用日历优化服务分析
        MeetingAnalysisResult meetingAnalysis =
            calendarService.analyzeMeetingRequest(meetingRequest, user);
        
        execution.addAction("analyze_meeting", meetingAnalysis);
        
        // 根据AI建议自动处理
        switch (meetingAnalysis.getRecommendation()) {
            case "accept":
                if (meetingAnalysis.getConfidenceScore() > 0.85) {
                    calendarService.acceptMeeting(meetingRequest, user);
                    emailService.sendMeetingAcceptance(email, user);
                    execution.addAction("auto_accept_meeting", "已自动接受会议");
                } else {
                    // 信心不够，提示用户确认
                    createMeetingDecisionCard(meetingRequest, meetingAnalysis, user);
                    execution.addAction("create_decision_card", "已创建决策卡片");
                }
                break;
                
            case "reschedule":
                // 生成改期建议邮件
                String rescheduleMessage = generateRescheduleMessage(
                    meetingAnalysis.getAlternativeTimes(), 
                    meetingAnalysis.getRecommendationReason()
                );
                emailService.sendRescheduleSuggestion(email, rescheduleMessage, user);
                execution.addAction("suggest_reschedule", "已发送改期建议");
                break;
                
            case "decline":
                if (meetingAnalysis.isCanDelegate()) {
                    // 婉拒并建议替代参会人
                    String declineMessage = String.format(
                        "感谢邀请。由于日程冲突，我建议由 %s 代表我参加此次会议。",
                        meetingAnalysis.getSuggestedDelegate()
                    );
                    emailService.sendMeetingDecline(email, declineMessage, user);
                    execution.addAction("delegate_meeting", "已婉拒并委托他人");
                }
                break;
        }
    }
    
    /**
     * 从截止日期创建任务
     */
    private void createTasksFromDeadlines(Email email, EmailAnalysisResult analysis,
                                         User user, AIWorkflowExecution execution) {
        for (ExtractedDeadline deadline : analysis.getExtractedDeadlines()) {
            Task task = new Task();
            task.setUserId(user.getId());
            task.setTitle(deadline.getDescription());
            task.setSourceType("email");
            task.setSourceId(email.getId());
            task.setDueDate(deadline.getDeadline());
            task.setPriority(analysis.getPriority().toString());
            
            taskService.save(task);
            execution.addAction("create_task", 
                String.format("已创建任务: %s", deadline.getDescription()));
        }
    }
    
    // 其他辅助方法...
}